package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Map;

/**
 * 设备数据属性信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-03
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据属性信息
     * 
     * @param id 设备数据属性信息主键
     * @return 设备数据属性信息
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据属性信息列表
     * 
     * @param deviceData 设备数据属性信息
     * @return 设备数据属性信息
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据属性信息
     * 
     * @param deviceData 设备数据属性信息
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据属性信息
     * 
     * @param deviceData 设备数据属性信息
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据属性信息
     * 
     * @param ids 需要删除的设备数据属性信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据属性信息信息
     * 
     * @param id 设备数据属性信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //拿到设备id,对数据库进行查询,没有查到则返回异常
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        //查询设备信息
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId));
        //对设备为空的情况进行判断
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        //设备存在,封装DeviceData数据
        iotMsgNotifyData.getBody().getServices().forEach(s->{
            Map<String, Object> properties = s.getProperties();
            //判断当前设备属性是否为空
            if (CollUtil.isEmpty(properties)) {
                return;
            }
            //处理时间数据
            String eventTimeStr = s.getEventTime();
            LocalDateTime time = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            //转化为东八区的时间
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(time);
            List<DeviceData> list = new ArrayList<>();
            //遍历设备属性集合
            properties.forEach((key,value)->{
                DeviceData deviceData = BeanUtil.toBean(device,DeviceData.class);
                deviceData.setId(null);
                deviceData.setAlarmTime(eventTime);
                deviceData.setFunctionId(key);
                deviceData.setDataValue(value.toString());
                deviceData.setAccessLocation(device.getBindingLocation());
                //deviceDataMapper.insertDeviceData(deviceData);
                list.add(deviceData);
            });
            this.saveBatch(list);
            //通过redis技术存储设备影子数据最新的值,每次仅修改小键和值
            redisTemplate.opsForHash().put(Constants.IOT_DEVICE_LAST_DATA,device.getIotId(), JSONUtil.toJsonStr(list));
        });
    }

}
